package com.huike.common.config;

import io.minio.*;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Configuration
@ConfigurationProperties("minio")
public class MinioTemplate {

    private String endpoint = "http://192.168.200.10:9000";
    private String accessKey = "minioadmin";
    private String secretKey = "minioadmin";
    private String bucket = "demo-bucket";

    @Autowired
    MinioClient minioClient;

    @Bean
    public MinioClient minioClient(){
        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint(endpoint)
                        .credentials(accessKey, secretKey)
                        .build();
        return minioClient;
    }

    /**
     * 对象上传
     * @param fileName
     * @param size
     * @param contentType
     * @param inputStream
     * @return
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    public String fileUpload(String fileName, Long size, String contentType, InputStream inputStream)throws IOException, NoSuchAlgorithmException, InvalidKeyException {

        String url = "";
        try {
            // Make 'asiatrip' bucket if not exist.
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
            } else {
                System.out.println("Bucket "+bucket+" already exists.");
            }

            //设置文件最终的路径和名称
            String objectName = "reggie/" + new SimpleDateFormat("yyyy/MM/dd").format(new Date())
                    + "/" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));

            // Upload '/home/user/Photos/asiaphotos.zip' as object name 'asiaphotos-2015.zip' to bucket
            // 'asiatrip'.
            //minioClient.uploadObject(
            //        UploadObjectArgs.builder()
            //                .bucket(bucket)
            //                .object(objectName)
            //                .filename(file.getAbsolutePath())
            //                .build());

            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucket).object(objectName).stream(
                            inputStream, size, -1)
                            .contentType(contentType)
                            .build());

            System.out.println(
                    fileName+" is successfully uploaded as "
                            + "object "+objectName+" to bucket "+bucket);
            url = endpoint+"/"+bucket+"/"+objectName;
            System.out.println("访问地址："+url);

        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
            System.out.println("HTTP trace: " + e.httpTrace());
        }
        return url;
    }

    /**
     * 下载
     * @param url
     * @return
     */
    public InputStream downLoad(String url){
        try{
            InputStream stream = minioClient.getObject(
                    GetObjectArgs.builder()
                            .bucket(bucket)
                            .object(url)
                            .build());
            // Read data from stream
            return stream;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
